package com.dmz.workflow.util;

import com.echronos.commons.Result;
import com.echronos.commons.enums.ErrorMsgEnum;
import com.echronos.commons.exception.BaseException;
import com.echronos.im.api.enums.FuncCode;
import com.echronos.im.api.enums.TemplateDataType;
import com.echronos.im.api.model.template.TemplateButton;
import com.echronos.im.api.model.template.TemplateData;
import com.echronos.im.api.model.template.TemplateMessage;
import com.echronos.imc.api.enums.GroupType;
import com.echronos.imc.api.enums.MsgType;
import com.echronos.imc.api.feign.IImcClient;
import com.echronos.imc.api.req.GroupCreateReq;
import com.echronos.imc.api.req.SendMsgReq;
import com.echronos.imc.api.resp.ImcSessionResp;
import com.dmz.workflow.constant.FormComponentConstants;
import com.dmz.workflow.constant.MessageConstants;
import com.dmz.workflow.dto.CommonFormComponent;
import com.dmz.workflow.dto.ProcessMessageBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 消息发送工具类
 */
@Component
public class ImcComponent {

    @Autowired
    private IImcClient iImcClient;

    /**
     * 发送群聊信息
     *
     * @param content      消息内容
     * @param senderId     发送消息的人
     * @param sessionId    发送到的会话ID
     * @param userNameList 接收消息的人员列表
     */
    public void imcContentSender(ProcessMessageBody content, Integer senderId, List<Integer> userNameList, Integer sessionId) {
        SendMsgReq smq = new SendMsgReq();
        smq.setMsgType(MsgType.TEMPLATE.value);
        smq.setSenderId(senderId);
        smq.setSessionId(sessionId);
        smq.setMsg(templateMessageWrapper(content));
        if (null != userNameList) {
            smq.setToUserIds(userNameList);
        }
        iImcClient.baseSend(smq);
    }

    /**
     * 发送华华商圈小助手
     *
     * @param content      消息内容
     * @param senderId     发送消息的人
     * @param userNameList 接收消息的人员列表
     */
    public void imcAssistantSender(ProcessMessageBody content, Integer senderId, List<Integer> userNameList, Integer sessionId) {
        SendMsgReq smq = new SendMsgReq();
        smq.setMsgType(MsgType.TEMPLATE.value);
        smq.setSenderId(senderId);
        smq.setMsg(templateMessageWrapper(content));
        if (null != userNameList) {
            smq.setToUserIds(userNameList);
        }
        iImcClient.sendMessageAssistant(smq);
    }

    /**
     * 创建圈聊
     *
     * @param companyId  公司ID
     * @param userIds    圈聊的成员
     * @param name       圈子的名称
     * @param createUser 创建圈聊的人
     * @return 圈聊信息
     */
    public ImcSessionResp imcCreateGroup(Integer companyId, List<Integer> userIds, String name, Integer createUser) {
        GroupCreateReq createReq = new GroupCreateReq();
        createReq.setCompanyId(companyId);
        createReq.setUserIds(userIds);
        createReq.setName(name);
        createReq.setSeeHistory(1);
        createReq.setGroupType(GroupType.INTERIOR.value);
        createReq.setCreateUserId(createUser);
        Result<ImcSessionResp> group = iImcClient.createGroup(createReq);
        return group.getData();
    }

    private TemplateMessage templateMessageWrapper(ProcessMessageBody content) {
        List<TemplateData> templateData = new ArrayList<>();
        Integer order = 1;
        processTemplateData(null, content.getContent(), null, TemplateDataType.DESC.value, order, templateData);
        LinkedHashSet<CommonFormComponent> formContent = content.getFormContent();
        for (CommonFormComponent commonFormComponent : formContent) {
            processFormComponentTemplateData(commonFormComponent, null, ++order, templateData);
        }
        Map<String, Object> dispatcherParams = new HashMap<>();
        dispatcherParams.put("processInstanceId", content.getProcessInstanceId());
        List<TemplateButton> templateButtons = new ArrayList<>();
        processTemplateButton(dispatcherParams, templateButtons);
        return TemplateMessage.builder()
                .title(MessageConstants.MESSAGE_TITLE)
                .funcCode(FuncCode.FLOW_ENGINE.code)
                .icon(MessageConstants.FLOW_ENGINE_ICON)
                .funcName(FuncCode.FLOW_ENGINE.desc)
                .args(dispatcherParams)
                .data(templateData)
                .button(templateButtons)
                .build();
    }

    private void processTemplateData(String name, Object value, String color, String type, Integer order, List<TemplateData> templateDataList) {
        TemplateData templateData = TemplateData.builder()
                .value(value)
                .order(order)
                .build();
        if (ObjectUtils.isNotEmpty(color)) {
            templateData.setColor(color);
        }
        if (ObjectUtils.isNotEmpty(name)) {
            templateData.setName(name);
        }
        if (ObjectUtils.isNotEmpty(type)) {
            templateData.setType(type);
        }
        templateDataList.add(templateData);
    }

    private void processFormComponentTemplateData(CommonFormComponent commonFormComponent, String color, Integer order, List<TemplateData> templateDataList) {
        TemplateData templateData = TemplateData.builder()
                .value(commonFormComponent.getValue())
                .order(order)
                .build();
        if (ObjectUtils.isNotEmpty(color)) {
            templateData.setColor(color);
        }
        if (ObjectUtils.isNotEmpty(commonFormComponent.getLabel())) {
            templateData.setName(commonFormComponent.getLabel());
        }
        if (commonFormComponent.getFormKey().contains(FormComponentConstants.DATE_RANGE_COMPONENT)
                || commonFormComponent.getFormKey().contains(FormComponentConstants.DATE_COMPONENT)) {
            templateData.setType(TemplateDataType.TIMESTAMP.value);
        } else {
            templateData.setType(TemplateDataType.STRING.value);
        }
        templateDataList.add(templateData);
    }

    private void processTemplateButton(Map<String, Object> dispatcherParams, List<TemplateButton> templateButtons) {
        TemplateButton button = TemplateButton.builder()
                .value(MessageConstants.MESSAGE_BUTTON_NAME)
                .postedValue(MessageConstants.MESSAGE_BUTTON_NAME)
                .color(MessageConstants.MESSAGE_BUTTON_COLOUR)
                .order("1")
                .type(MessageConstants.MESSAGE_BUTTON_GOTO_TYPE)
                .disabled(false)
                .url(FuncCode.FLOW_ENGINE.code)
                .args(dispatcherParams)
                .build();
        templateButtons.add(button);
    }
}
